<?php
/**
 * soap Request Base
 */

namespace request;

use request\Request;
use think\Log;

class SoapRequest
{
    public function run(Request $request, $options = []) {
        try {
            $params = $request->getParams();

            $this->log('Url', $request->getUrl());
            $soapClient = new \SoapClient($request->getUrl(), $options);

            foreach($params as $key => $val) {
                $this->log('Params', ' [ '.$key.' ] '. (is_scalar($val) ? $val : 'Array '. json_encode($val, JSON_UNESCAPED_UNICODE)));
            }

            $result = $soapClient->__call($request->getApiMethodName(), array($params));
            $result = $result->{$request->getResultName()};
            foreach ($request->getOtherResultNames() as $resultName) {
                $request->{'set'.ucfirst($resultName)}($result->$resultName);
            }

            $this->log('Result', $result);

            $request->setStatusCode(200);
            $request->setResponse($result);
        } catch (\SoapFault $e) {

            $this->log('Error', $e->getMessage());
            $request->setStatusCode($e->getCode());
            $request->setMessage($e->getMessage());

            throw new RequestException($e->getMessage());
        }

        return $request;
    }


    /**
     * 验证接口地址是否可用
     * @param $url
     * @param int $timeout
     * @return bool
     */
    protected function checkApiUrl($url, $timeout = 3){
        $handle = curl_init();

        if (stripos($url, 'https://') !== false) {
            curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($handle, CURLOPT_SSLVERSION, 1);
        }

        curl_setopt($handle, CURLOPT_URL, $url);
        curl_setopt($handle, CURLOPT_NOBODY, true);
        curl_setopt($handle, CURLOPT_TIMEOUT, $timeout);//设置默认超时时间为3秒
        $result = curl_exec($handle);

        return (boolean)$result;
    }

    protected function log($type, $content) {
        !is_scalar($content) and $content = json_encode($content, JSON_UNESCAPED_UNICODE);
        $content = date('Y-m-d H:i:s | ').$type.': '.$content;
        $content .= "\r\n";
        file_rput_contents(RUNTIME_PATH.'/soap_log/'.date('Ym/d').'.log', $content, FILE_APPEND);
    }
}